<template>
  <div class="page goods-list">
    <StoreChoice
      ref="StoreChoice"
      :current="[]"
      :multipleChoice="false"
      @listenToStoreSelect="getSelectStoreValue"
      :hasTotal="true"
      reqUrl="/newapp/shop/getMarketShopSelect.do"
    />
    <div class="scroll-view">
      <customHeader middleTitle="商品管理" @leftCallBack="handleBack" />
         <div class="store-box" @click="handleClickSelectStore">
          <span>门店：{{storeName}}</span>
          <i v-if="roleInfo.manyShopFlag" class="zhk-list_rarrow"></i>
        </div>
        <ul class="tab-bar">
          <li
            v-for="(status,index) in statusList"
            :class="{active:currStatus==status.value}"
            :key="index"
            @click="handleStatusChange(status)"
          >
            <span>{{status.label}}</span>
          </li>
        </ul>
      <div class="page-body">
        <no-data msg="没有符合条件的商品" v-if="!loading&&list.length==0"></no-data>
        <ul
          class="list-box"
          v-infinite-scroll="loadMore"
          infinite-scroll-disabled="loading"
          infinite-scroll-distance="30"
        >
          <li v-for="(item,index) in list" :key="index">
            <div class="top">
              <img
                :src="item['goodsSalesSkuModel']?imgUrlFormate(item['goodsSalesSkuModel'].cover):''"
                alt
                class="left"
              />
              <div class="right">
                <div class="goods-name">{{item.goodsName}}</div>
                <div class="price">{{item.price}}</div>
                <div class="count-box">
                  <div class="stock">剩余库存：{{item.inventory-item.salesNums}}</div>
                  <div class="salecount">销量：{{item.salesNums}}</div>
                </div>
              </div>
            </div>
            <div class="bottom">
              <div class="btn" @click="linkToAdd(1,item.goodsId)">编辑</div>
              <div
                class="btn"
                @click="updateStatusChange(item.goodsId,1)"
                v-if="item.status==2||item.status==0"
              >上架</div>
              <div class="btn" @click="updateStatusChange(item.goodsId,2)" v-if="item.status==1">下架</div>
              <!-- <div class="btn" @click="linkToSpread(item.goodsId)" v-if="item.status==1">推广</div> -->
            </div>
          </li>
          <p v-show="loading" class="page-infinite-loading">
            <mt-spinner :style="{display:'inline-block'}" type="fading-circle"></mt-spinner>
          </p>
          <div v-show="noMore&&!loading&&list.length!==0" class="no-more">
            <span>已经全部加载完毕</span>
          </div>
        </ul>
      </div>
      <div class="btn-add" @click="linkToAdd(0)">新增商品</div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import customHeader from '../../components/header/header';
import noData from "../../components/noData/noData";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import { Toast } from 'mint-ui';
import config from "../../base/profile/config.json";
import jsAuthority from "../../tools/jsAuthority.js";
import jsBridge from '../../tools/jsBridge.js';
export default {
  name: 'goodsList',
  data() {
    return {
      authAddOrEdit: false,
      authStandUpAndDown: false,
      storeName: "全部门店",
      pageSize: 10,
      currentPage: 1,
      loading: false,
      noMore: false,
      statusList: [{ label: "出售中(0)", value: 1 }, { label: "待上架(0)", value: 0 }, { label: "已下架(0)", value: 2 }, { label: "已售完(0)", value: 3 }],
      currStatus: 1,//状态 0:待上架 1:售卖中 2:下架 3:已售罄 4:暂停核销
      list: [],
      roleInfo: {}
    };
  },
  methods: {
    handleBack() {
      if (this.$refs.StoreChoice && this.$refs.StoreChoice.popupVisible) {
        this.$refs.StoreChoice.back();
      } else {
        if (String(this.$route.query.close) == 'true') {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    imgUrlFormate(url) {
      return CommonUtil.imgUrlFormate(url, config.previewUrlPrefix)
    },
    handleClickSelectStore() {
      this.$refs.StoreChoice.popupShow();
    },
    getSelectStoreValue(value, storeName) {
      var shopId = value[0].selectKey;
      this.shopId = shopId == "all" ? [] : [shopId];
      this.storeName = storeName;
      this.currentPage = 1;
      this.getData();
    },
    handleStatusChange(v) {
      if (this.currStatus == v.value) {
        return;
      }
      this.currStatus = v.value;
      this.currentPage = 1;
      this.getData();
    },
    //修改状态
    updateStatusChange(id, status) {
      if (!this.authStandUpAndDown) {
        Toast("暂无权限");
        return;
      }
      if (this.loading) {
        return;
      }
      this.loading = true;
      let params = { goodsId: id, status: status, operatorId: "" };
      this.ajax({
        url: "/newapp/goods/service/manageGoodsStatus.do",
        type: "post",
        data: params,
        controlLoading: true
      })
        .then(res => {
          this.loading = false;
          if (res.success && res.resultObject) {
            this.currentPage = 1;
            this.getData();
            Toast("操作成功");
          } else {
            Toast(res.msg);
          }
        })
    },

    //无限加载
    loadMore() {
      if (this.loading || this.noMore) {
        return;
      }
      this.getData();
    },
    getData() {
      if (this.loading) {
        return;
      }
      this.loading = true;
      const url = "/newapp/goods/service/queryGoodsList.do";
      const params = {
        shopIds: this.shopId ? this.shopId : [],
        queryStatus: this.currStatus,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      };
      if (this.currentPage == 1) {
        this.list = [];
      }
      this.ajax({
        url: url,
        type: "post",
        data: params,
        controlLoading: false
      })
        .then(res => {
          this.loading = false;
          this.noMore = false;
          if (res.success) {
            const data = res.resultObject;
            const goodsNumberModel = data.goodsNumberModel;
            //最后一页将noMore设置为true
            if (data && data["page"] && data['page']['list'] && data['page']['list'].length > 0) {
              const page = data['page'];
              this.list = this.list.concat(page['list']);
               if (page.dataCount) {
                this.noMore = Math.ceil(page.dataCount / this.pageSize) === this.currentPage ? true : false;
              } else {
                this.noMore = true;
              }
              this.currentPage = this.currentPage + 1;
            } else {
              this.noMore = true;
            }
            let count = "0";
            if (goodsNumberModel) {
              this.statusList[0].label = "出售中(" + (goodsNumberModel['onlineum']) + ")";
              this.statusList[1].label = "待上架(" + (goodsNumberModel['toSellNum']) + ")";
              this.statusList[2].label = "已下架(" + (goodsNumberModel['offOnlineNum']) + ")";
              this.statusList[3].label = "已售完(" + (goodsNumberModel['sellOutNum']) + ")";
            } else {
              this.statusList[0].label = "出售中(0)";
              this.statusList[1].label = "待上架(0)";
              this.statusList[2].label = "已下架(0)";
              this.statusList[3].label = "已售完(0)";
            }

          } else {
            this.noMore = true;
            Toast(res.msg);
          }
        })
        .catch((err) => {
          this.loading = false;
          this.noMore = true;
        });
    },
    linkToAdd(type, id) {
      if (!this.authAddOrEdit) {
        Toast("暂无权限");
        return;
      }
      const param = { type: type };
      if (type == 1) {
        param.id = id;
      }
      this.$router.push({ path: '/goodsDataBoard/goodsManage/edit', query: param });
    },
    linkToSpread(id) {
      this.$router.push({ path: '/goodsDataBoard/goodsManage/spread', query: { id: id } });
    },
    getAuth() {
      jsAuthority.checkedSuccess(() => {
        this.authAddOrEdit = jsAuthority.checked(
          "app.goodsManage.addOrEdit"
        );
      });
      jsAuthority.checkedSuccess(() => {
        this.authStandUpAndDown = jsAuthority.checked(
          "app.goodsManage.standUpAndDown"
        );
      });
      jsAuthority.checkedSuccess(() => {
        this.authScan = jsAuthority.checked(
          "app.goodsManage.scan"
        );
      });
      jsAuthority.checkedSuccess(() => {
        this.authDashBoard = jsAuthority.checked(
          "app.goodsManage.dashBoard"
        );
      });
    }
  },
  components: {
    customHeader,
    noData,
    StoreChoice
  },
  created() {
    this.getAuth();
    CommonUtil.getUserInfo().then(userInfo => {
      this.roleInfo = userInfo;
      if (!this.roleInfo.manyShopFlag) {
        this.shopId = [this.roleInfo.yzShopId];
        this.storeName = this.roleInfo.shopName;
      }
    });
  },
};
</script>
<style lang='scss' scoped>
@import "goodsManage";
</style>
